#coding=utf-8
from django import forms
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView
from models import *

class CustomerFieldPlugin(BaseAdminPlugin):
    
    def init_request(self, *args, **kwargs):
        return not self.user.is_superuser

    def get_field_attrs(self, attrs, db_field, **kwargs):
        if issubclass(self.model, UserBaseModel) and db_field.name == 'user':
            return {'widget': forms.HiddenInput}
        if hasattr(db_field, "rel") and db_field.rel and issubclass(db_field.rel.to, UserBaseModel):
            attrs['queryset'] = db_field.rel.to._default_manager.get_query_set().filter(user=self.user)
        return attrs

    def get_form_datas(self, datas):
        if issubclass(self.model, UserBaseModel) and datas.has_key('data'):
            datas['data']['user'] = self.user.id
        return datas

site.register_plugin(CustomerFieldPlugin, ModelFormAdminView)